package com.taobao.top.demo.getData;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import com.taobao.top.demo.common.DemoConstant;
import com.taobao.top.demo.common.Util;
import com.taobao.top.demo.dataobject.PropImg;
import com.taobao.top.demo.exception.DemoException;
/**
 * 调用 taobao.item.propimg.upload
 * 模拟POST请求，更新属性图片
 * @author Jessica
 *
 */
public class UpdateImgUtil{

	/**
	 * 更新属性图片
	 * @param iid 商品的iid
	 * @param file 待更新图片的内容
	 * @param sessionKey
	 * @param propImg 属性图片
	 * @param name 待更新属性图片的名字
	 * @param path 待更新的属性图片的路径
	 * @return
	 * @throws DemoException
	 */
	public static String UpdateImg(String iid,byte[] file,String sessionKey,PropImg propImg,String name,String path) throws DemoException{
		TreeMap<String,String> apiparamsMap = new TreeMap<String,String>();
		//组装协议参数
		apiparamsMap.put("method", "taobao.item.propimg.upload");
		apiparamsMap.put("format", "xml");
		apiparamsMap.put("v", "2.0");
		apiparamsMap.put("app_key",DemoConstant.APP_KEY);
		apiparamsMap.put("session", sessionKey);
		apiparamsMap.put("timestamp", new SimpleDateFormat(
		"yyyy-MM-dd HH:mm:ss").format(new Date()));
		//组装应用参数
		//更新图片，需要传递id，添加图片，则不需要传递id
		if(propImg.getPropimgId()!= null){
			apiparamsMap.put("id", propImg.getPropimgId());
		}
		apiparamsMap.put("iid", iid);
		apiparamsMap.put("properties", propImg.getProperties());
		//生成签名
		String sign = Util.sign(apiparamsMap, DemoConstant.APP_SERCET);
		//组装协议参数sign
		apiparamsMap.put("sign", sign);
		
		//按照HTTP的协议内容标准格式发送信息
		String BOUNDARY = "---------------------------7d4a6d158c9"; // 分隔符
		StringBuffer sb = new StringBuffer();
		// 发送每个字段:
		for (Iterator<Map.Entry<String, String>> it = apiparamsMap.entrySet().iterator(); it.hasNext();) {
			Map.Entry<String, String> e = it.next();
			sb = sb.append("--");
			sb = sb.append(BOUNDARY);
			sb = sb.append("\r\n");
			sb = sb.append("Content-Disposition: form-data; name=\""+ e.getKey() + "\"\r\n\r\n");
			sb = sb.append(e.getValue());
			sb = sb.append("\r\n");
		}
		// 发送图片:
		sb = sb.append("--");
		sb = sb.append(BOUNDARY);
		sb = sb.append("\r\n");
		sb = sb.append("Content-Disposition: form-data; name=\""+name+"\"; filename=\""+path+"\"\r\n");
		sb = sb.append("Content-Type: Content-Type: image/jpeg\r\n\r\n");
		byte[] data = sb.toString().getBytes();
		byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
		
		URL url = null;
		HttpURLConnection connection = null;
		try {
			//建立连接
			url = new URL(DemoConstant.SANDBOX_URL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+BOUNDARY);
			connection.setRequestProperty("Content-Length", String.valueOf(data.length + file.length + end_data.length));
			connection.setUseCaches(false);
			connection.connect();

			//发送参数
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			out.write(data);
			out.write(file);
			out.write(end_data);
		
			out.flush();
			out.close();

			//获得结果
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection
					.getInputStream(), "utf-8"));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			reader.close();
			return buffer.toString();
		} catch (IOException e) {
			throw new DemoException("API调用失败");
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
	}
	
}
